﻿Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient

Public Class frmConnect
    Private servers As SqlDataSourceEnumerator
    Private tableServers As DataTable
    Private server As String

    Public Sub New()
        InitializeComponent()
        servers = SqlDataSourceEnumerator.Instance
        tableServers = New DataTable()
    End Sub
    
    Private Sub cmbServerName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbServerName.Click
        If tableServers.Rows.Count = 0 Then
            tableServers = servers.GetDataSources()
            Dim listServers As List(Of String) = New List(Of String)
            For Each rowServer As DataRow In tableServers.Rows
                If String.IsNullOrEmpty(rowServer("InstanceName").ToString()) Then
                    listServers.Add(rowServer("ServerName").ToString())
                Else
                    listServers.Add(rowServer("ServerName") & "\" & rowServer("InstanceName"))
                End If
            Next
            cmbServerName.DataSource = listServers
        End If
    End Sub

    Private Sub cmbDuLieu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbDuLieu.Click
        Dim listDataBases As List(Of String) = New List(Of String)
        Dim connectString As String
        Dim selectSQL As String
        If Me.cmbServerName.Text = "" Then
            MsgBox("Bạn vui lòng chọn máy chủ SQL")
            Return
        End If
        server = cmbServerName.Text
        connectString = "Data Source=" & server & " ;Integrated Security=True;Initial Catalog=master"
        Using con As New SqlConnection(connectString)
            con.Open()
            selectSQL = "select name from sys.databases;"
            Dim com As SqlCommand = New SqlCommand(selectSQL, con)
            Dim dr As SqlDataReader = com.ExecuteReader()
            While (dr.Read())
                listDataBases.Add(dr(0).ToString())
            End While
            cmbDuLieu.DataSource = listDataBases
        End Using
    End Sub

    Private Sub txtThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtThoat.Click
        Me.Close()
    End Sub
End Class